import axios from "axios";
import queryApi from "../api/query";
import AWS from "aws-sdk";
import mime from "mime";

const DEFAULT_REGION = "cn-northwest-1";

const idCreator = (len, radix) => {
  const chars =
    "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("");
  let temp = [],
    i;
  radix = radix || chars.length;
  if (len) {
    for (i = 0; i < len; i++) temp[i] = chars[0 | (Math.random() * radix)];
  } else {
    var r;
    temp[8] = temp[13] = temp[18] = temp[23] = "-";
    temp[14] = "4";
    for (i = 0; i < 36; i++) {
      if (!temp[i]) {
        r = 0 | (Math.random() * 16);
        temp[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r];
      }
    }
  }
  return temp.join("");
};

const getFileType = (uri) => {
  let mimeType = "";
  const fileType = uri.split(".").pop();
  if (fileType == "jpg") {
    mimeType = "image/" + fileType;
  } else {
    mimeType = mime.getType(fileType);
  }
  return mimeType;
};

const getAccessConfig = async () => {
  try {
    const result = await queryApi.get("/aws");
    const credential = result.data.credential;
    AWS.config = new AWS.Config({
      accessKeyId: credential.AccessKeyId,
      secretAccessKey: credential.SecretAccessKey,
      sessionToken: credential.SessionToken,
      region: DEFAULT_REGION,
    });
    console.log("获取凭证成功");
    return new AWS.S3();
  } catch (err) {
    console.log("获取凭证失败", err);
  }
};

const getFileKey = (uri) => {
  const fileId = idCreator(16, 32);
  const type = uri.split(".").pop();
  const key = `${fileId}.${type}`;
  return key;
};

export const uploadFileByS3 = async (file) => {
  try {
    const S3Instance = await getAccessConfig();
    let fileUrls = [];
    let fileUrl;
    if (Array.isArray(file)) {
      await Promise.all(
        file.map(async (item) => {
          const mimeType = getFileType(item.uri);
          const fileKey = getFileKey(item.uri);
          const response = await fetch(item.uri);
          const blob = await response.blob();
          const params = {
            Body: blob,
            ContentType: mimeType,
            Bucket: "consult",
            Key: fileKey,
          };
          await S3Instance.putObject(params)
            .promise()
            .then((res) => {
              fileUrls.push(fileKey);
            });
        })
      );

      return fileUrls;
    } else {
      const mimeType = getFileType(file);
      const fileKey = getFileKey(file);
      const response = await fetch(file);
      const blob = await response.blob();
      const params = {
        Body: blob,
        ContentType: mimeType,
        Bucket: "consult",
        Key: fileKey,
      };

      await S3Instance.putObject(params)
        .promise()
        .then((res) => {
          fileUrl = fileKey;
        });
      console.log("S3上传图片成功");
      return fileUrl;
    }
  } catch (err) {
    console.log("S3上传图片失败", err);
  }
};

//fileKey  单个Key  或者数组Key
export const deleteFileByS3 = async (fileKey) => {
  try {
    const S3Instance = await getAccessConfig();

    if (Array.isArray(fileKey)) {
      const objects = fileKey.map((key) => ({ Key: key }));
      let params = {
        Bucket: "consult",
        Delete: { Objects: objects },
      };
      await S3Instance.deleteObjects(params)
        .promise()
        .then(() => {
          console.log("删除图片成功");
        })
        .catch((err) => {
          console.log("删除图片失败---", err);
        });
    } else {
      let params = {
        Bucket: "consult",
        Key: fileKey,
      };
      await S3Instance.deleteObject(params)
        .promise()
        .then(() => {
          console.log("删除图片成功");
        })
        .catch((err) => {
          console.log("删除图片失败---", err);
        });
    }
  } catch (err) {
    console.log("S3删除图片失败", err);
  }
};
